import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';

axios.defaults.baseURL = '/api';

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.data) {
      let code = response.data.code;
      let message = '业务操作失败: ' + response.data.message;
      if (code != 'OK') {
        Message.error({
          content: message,
          duration: 5 * 1000,
        });
      }
    }

    return response;
  },
  (error) => {
    const { status, statusText, data } = error.response;
    let msg = '';
    if (data) {
      let res = typeof data === 'string' ? JSON.parse(data) : data;
      if (res && res.message) {
        msg = res.message;
      }
    }
    switch (status) {
      case 400:
        msg = '无效的请求数据格式';
        break;
      case 401:
        msg = '无效的请求权限信息';
        break;
      case 403:
        msg = '禁止请求: ' + msg;
        break;
      case 404:
        msg = '无效的请求地址';
        break;
      case 500:
        msg = '服务器异常: ' + msg;
        break;
      case 501:
        msg = '服务器异常: ' + msg;
        break;
      default:
        msg = statusText;
        break;
    }
    Message.error({
      content: msg,
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
